<template>
  <div class="house-detail">
    <el-card v-loading="loading" element-loading-text="加载中...">
      <!-- 图片轮播 -->
      <el-carousel v-if="images.length > 0" height="400px">
        <el-carousel-item v-for="(image, index) in images" :key="index">
          <img :src="image" class="carousel-image" />
        </el-carousel-item>
      </el-carousel>

      <!-- 房源基本信息 -->
      <div class="title-section">
        <h2>{{ title }}</h2>
        <div class="status">
          <el-tag type="success" size="small">可租</el-tag>
          <el-tag type="danger" size="small" v-if="isCollected">已收藏</el-tag>
        </div>
        <div class="price">
          <span class="amount">¥{{ rent }}/月</span>
          <span class="deposit">押金：¥{{ deposit }}</span>
        </div>
      </div>

      <!-- 房源地址 -->
      <div class="address-section">
        <el-icon><Location /></el-icon>
        <span>{{ address }}</span>
        <a class="map-link" href="#">查看地图</a>
      </div>

      <!-- 房源属性 -->
      <div class="property-info">
        <div class="info-item">
          <el-icon><House /></el-icon>
          <span class="label">房型</span>
          <span class="value">{{ layout }}</span>
        </div>
        <div class="info-item">
          <el-icon><OfficeBuilding /></el-icon>
          <span class="label">面积</span>
          <span class="value">{{ area }}㎡</span>
        </div>
        <div class="info-item">
          <el-icon><School /></el-icon>
          <span class="label">楼层</span>
          <span class="value">{{ floor }}</span>
        </div>
        <div class="info-item">
          <el-icon><Position /></el-icon>
          <span class="label">朝向</span>
          <span class="value">{{ facing }}</span>
        </div>
      </div>

      <!-- 配套设施 -->
      <div class="facilities-section">
        <h3>配套设施</h3>
        <div class="facility-list">
          <div v-for="(value, key) in facilities" :key="key" class="facility-item" :class="{ 'available': value }">
            <el-icon>
              <component :is="facilityIcons[key]" />
            </el-icon>
            <span>{{ facilityLabels[key] }}</span>
          </div>
        </div>
      </div>

      <!-- 房源描述 -->
      <div class="description-section">
        <h3>房源描述</h3>
        <p>{{ description }}</p>
      </div>

      <!-- 评论列表 -->
      <div class="comments-section">
        <h3>评论列表</h3>
        <div v-if="comments.length > 0">
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-header">
              <span class="username">{{ comment.username }}</span>
              <span class="time">{{ comment.time }}</span>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
            <div class="comment-rating">评分: {{ comment.rating }}</div>
          </div>
        </div>
        <div v-else class="no-comments">暂无评论</div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="contactLandlord">
          <el-icon><Message /></el-icon>
          联系房东
        </el-button>
        <el-button type="success" @click="goToOrder">
          <el-icon><Check /></el-icon>
          立即预订
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import {
  Location,
  House,
  OfficeBuilding,
  School,
  Position,
  Message,
  Check,
  Monitor,
  Refrigerator,
  Goods,
  HomeFilled,
  Notification,
  Sunny,
  ColdDrink
} from '@element-plus/icons-vue';

const router = useRouter();
const route = useRoute();
const loading = ref(false);

// 房源数据
const title = ref('');
const rent = ref(0);
const deposit = ref(0);
const address = ref('');
const layout = ref('');
const area = ref(0);
const floor = ref('');
const facing = ref('');
const description = ref('');
const facilities = ref({
  wifi: false,
  heating: false,
  washing_machine: false,
  air_conditioning: false
});
const images = ref([]);
const isCollected = ref(false);
const comments = ref([]);

// 设施图标映射
const facilityIcons = {
  wifi: Monitor,
  heating: Sunny,
  washing_machine: Goods,
  air_conditioning: ColdDrink
};

// 设施标签映射
const facilityLabels = {
  wifi: 'WiFi',
  heating: '暖气',
  washing_machine: '洗衣机',
  air_conditioning: '空调'
};

// 获取房源详情
const fetchHouseDetail = async () => {
  console.log('Fetching house detail...');
  loading.value = true;
  try {
    const houseId = route.query.id;
    console.log('House ID:', houseId);

    if (!houseId) {
      ElMessage.error('房源ID不能为空');
      router.push('/');
      return;
    }

    const response = await axios.get(`http://127.0.0.1:8000/users/house/`, {
      params: {
        id: houseId
      },
      headers: {
        Authorization: localStorage.getItem('token')
      }
    });
    console.log('API Response:', response.data);

    if (response.data.code === 200) {
      const data = response.data.data;
      title.value = data.title;
      rent.value = parseFloat(data.price);
      deposit.value = parseFloat(data.deposit);
      address.value = `${data.city}${data.district}${data.address}`;
      layout.value = data.house_type;
      area.value = parseFloat(data.area);
      floor.value = `${data.floor}/${data.total_floor}层`;
      facing.value = getFacingText(data.orientation);
      description.value = data.description;
      images.value = data.images || [];

      // 处理设施数据
      if (data.facilities && typeof data.facilities === 'object') {
        Object.keys(facilities.value).forEach(key => {
          facilities.value[key] = !!data.facilities[key];
        });
      }

      isCollected.value = false; // 这个需要单独接口获取
    }
  } catch (error) {
    console.error('获取房源详情失败:', error);
    if (error.response && error.response.status === 404) {
      ElMessage.error('房源不存在或已下架');
      router.push('/'); // 房源不存在时返回首页
    } else {
      ElMessage.error('获取房源详情失败，请稍后重试');
    }
  } finally {
    loading.value = false;
  }
};

// 获取朝向文字
const getFacingText = (orientation) => {
  const facingMap = {
    'east': '东',
    'south': '南',
    'west': '西',
    'north': '北',
    'southeast': '东南',
    'southwest': '西南',
    'northeast': '东北',
    'northwest': '西北'
  };
  return facingMap[orientation] || '未知';
};

// 联系房东
const contactLandlord = () => {
  ElMessage.info('联系房东功能开发中...')
}

// 立即预订
const goToOrder = async () => {
  try {
    const houseId = route.query.id
    if (!houseId) {
      ElMessage.error('房源ID不能为空')
      return
    }

    const token = localStorage.getItem('token')
    const userId = localStorage.getItem('userid')
    if (!token || !userId) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    // 确保token格式正确
    const tokenToUse = token.startsWith('Bearer ') ? token : `Bearer ${token}`

    // 计算合同起止时间
    const startDate = new Date()
    const endDate = new Date()
    endDate.setMonth(endDate.getMonth() + 12) // 默认12个月租期

    // 创建合同
    const response = await axios.post('http://127.0.0.1:8000/users/contract/create/', {
      contract_type: 'RENT',
      house_id: parseInt(houseId),
      tenant_id: parseInt(userId),
      total_amount: rent.value * 12, // 年总租金
      deposit: deposit.value,
      effective_time: startDate.toISOString().split('T')[0],
      expire_time: endDate.toISOString().split('T')[0],
      remarks: '',
      // 租赁合同特有字段
      rent: rent.value,
      payment_cycle: 'MONTHLY',
      payment_due_day: 5, // 默认每月5号付款
      grace_period: 3,
      early_termination_allowed: true
    }, {
      headers: {
        'Authorization': tokenToUse,
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 200) {
      ElMessage.success('预订成功！')
      // 跳转到合同详情页
      router.push({
        path: '/contract',
        query: {
          id: response.data.data.contract_id
        }
      })
    } else {
      ElMessage.error(response.data.msg || '预订失败，请稍后重试')
    }
  } catch (error) {
    console.error('预订失败:', error)
    if (error.response) {
      switch (error.response.status) {
        case 400:
          ElMessage.error('请求参数错误：' + (error.response.data.msg || '请检查输入'))
          break
        case 401:
          ElMessage.error('登录已过期，请重新登录')
          router.push('/login')
          break
        case 403:
          ElMessage.error('没有权限执行此操作，请确保已登录')
          router.push('/login')
          break
        case 500:
          ElMessage.error('服务器错误，请稍后重试')
          break
        default:
          ElMessage.error(error.response.data.msg || '预订失败，请稍后重试')
      }
    } else if (error.request) {
      ElMessage.error('网络请求失败，请检查网络连接')
    } else {
      ElMessage.error('发生未知错误，请稍后重试')
    }
  }
}

// 获取房源评论
const fetchComments = async () => {
  try {
    const houseId = route.query.id;
    if (!houseId) return;

    const response = await axios.get(`http://127.0.0.1:8000/users/api/comments/`);
    if (response.data.success) {
      // 只保留type=好评的评论
      comments.value = response.data.data.filter(comment => comment.type === '好评');
    }
  } catch (error) {
    console.error('获取评论失败:', error);
  }
};

// 页面加载时获取房源详情
onMounted(() => {
  fetchHouseDetail();
  fetchComments();
});
</script>

<style scoped>
.house-detail {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.title-section {
  margin: 20px 0;
}

.title-section h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #333;
}

.status {
  margin-bottom: 10px;
}

.status .el-tag {
  margin-right: 10px;
}

.price {
  color: #ff4d4f;
}

.price .amount {
  font-size: 24px;
  font-weight: bold;
  margin-right: 10px;
}

.price .deposit {
  font-size: 14px;
  color: #666;
}

.address-section {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  color: #666;
}

.map-link {
  margin-left: 10px;
  color: #1890ff;
  text-decoration: none;
}

.property-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin: 20px 0;
  padding: 20px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.info-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.info-item .el-icon {
  font-size: 24px;
  color: #1890ff;
  margin-bottom: 8px;
}

.info-item .label {
  color: #999;
  margin-bottom: 4px;
}

.info-item .value {
  color: #333;
  font-size: 16px;
}

.facilities-section {
  margin: 20px 0;
}

.facilities-section h3,
.description-section h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  color: #333;
}

.facility-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
}

.facility-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  border-radius: 4px;
  background: #f5f7fa;
  color: #999;
}

.facility-item.available {
  background: #e6f7ff;
  color: #1890ff;
}

.description-section {
  margin: 20px 0;
}

.description-section p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

.comments-section {
  margin: 20px 0;
}

.comments-section h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  color: #333;
}

.comment-item {
  margin-bottom: 16px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.comment-header .username {
  font-size: 16px;
  font-weight: bold;
}

.comment-header .time {
  font-size: 14px;
  color: #999;
}

.comment-content {
  margin-bottom: 8px;
}

.comment-rating {
  font-size: 14px;
  color: #999;
}

.no-comments {
  text-align: center;
  color: #999;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding-top: 20px;
  margin-top: 20px;
  border-top: 1px solid #eee;
}

.action-buttons .el-button {
  min-width: 140px;
  height: 40px;
  font-size: 16px;
}

.action-buttons .el-button .el-icon {
  margin-right: 8px;
}
</style>